package cs2340.klondike.TaskFudger;

import java.io.IOException; 

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.ForeignCollection;

import db.DatabaseHelper;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Address;
import android.location.Geocoder;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import models.*;

/**
 * This class creates a new task if the Create Button is clicked.
 * If the Cancel Button is clicked then it goes back to the
 * previous screen.
 * @author Grishma Patel
 *
 */
public class NewTaskActivity extends OrmLiteBaseActivity<DatabaseHelper>
{
	private Button registerButton;
	private Button cancelButton;
	private Button deleteButton;
	private EditText teaserField;
	private EditText descriptionField;
	private EditText commentField;
	private Button duedateButton;
	private EditText locationAddress;
	private Button getCurrentLocation;
	private CheckBox completed;
	private CheckBox doesRecur;
	private TextView teaserMessage;
	private Spinner categorySpinner;
	private Spinner prioritySpinner;
	static final int DATE_DIALOG_ID = 0;
	private int day;
	private int month;
	private int year;
	private Date taskDate;
	private List<Category> categories;
	private boolean editing;
	private Task thisTask;
	
    /**
     * This method creates a dialog for the user to pick a date.
     */
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
    {
    	public void onDateSet(DatePicker view, int inputyear, int monthOfYear, int dayOfMonth)
    	{
    		year = inputyear;
            month = monthOfYear;
            day = dayOfMonth;
            taskDate = new Date(year,month,day);
            updateDisplay();
        }
    };


	/**
	 * This method updates the due date that is being displayed on the screen
	 */
	private void updateDisplay() 
	{
	    duedateButton.setText(new StringBuilder()
	         // Month is 0 based so add 1
	         .append(month + 1).append("-")
	         .append(day).append("-")
	         .append(year).append(" "));
	}		
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	protected Dialog onCreateDialog(int id) 
	{
	    switch (id) 
	    {
	    	case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, year, month, day);
	    }
	    
	    return null;
	}
	
	/* (non-Javadoc)
	 * @see com.j256.ormlite.android.apptools.OrmLiteBaseActivity#onCreate(android.os.Bundle)
	 */
	public void onCreate(Bundle savedInstanceState)
	{
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.new_task);
	        
	        registerButton = (Button)findViewById(R.id.createTask);
	        cancelButton = (Button)findViewById(R.id.cancelCreateTask);
	        deleteButton = (Button)findViewById(R.id.deleteTask);
	        teaserField = (EditText)findViewById(R.id.teaser);
	        descriptionField = (EditText)findViewById(R.id.description);
	        commentField = (EditText)findViewById(R.id.comments);
	        duedateButton = (Button)findViewById(R.id.dueDate);
	        locationAddress = (EditText)findViewById(R.id.locationAddress);
	        getCurrentLocation = (Button)findViewById(R.id.getCurrentLocation);
	        completed = (CheckBox)findViewById(R.id.completed);
	        doesRecur = (CheckBox)findViewById(R.id.doesRecur);
	        teaserMessage = (TextView)findViewById(R.id.teaserLabel);
	        categorySpinner = (Spinner)findViewById(R.id.category); 
	        prioritySpinner = (Spinner)findViewById(R.id.prioritySpinner);
	        
	        editing = this.getIntent().hasExtra("TASK_ID");
	        
	        deleteButton.setText("Delete");
	        cancelButton.setText("Cancel");
	        
	        if (editing){
	        	thisTask = Task.getDefaultDao().queryForId(this.getIntent().getIntExtra("TASK_ID",0));
 	        	teaserField.setText(thisTask.getTeaser());
 	        	descriptionField.setText(thisTask.getDescription());
 	        	commentField.setText(thisTask.getComments());
 	        	if (thisTask.getDueDate() != null){
	 	        	taskDate = thisTask.getDueDate();
	 	        	day = taskDate.getDay();
	 	        	month = taskDate.getMonth();
	 	        	year = taskDate.getYear();
	 	        	updateDisplay();
	 	        }
 	        	if (thisTask.getCategory() != null){
 	        		categorySpinner.setSelection(categories.lastIndexOf(thisTask.getCategory()) + 1);
 	        	}
 	        	prioritySpinner.setSelection(thisTask.getPriority());
 	        	if (thisTask.getLocation() != null){
 	        		locationAddress.setText(thisTask.getLocation().toString());
 	        	}
 	        	if (thisTask.isCompleted()){
 	        		completed.setChecked(true);
 	        	}
 	        	if (thisTask.isDoesRecur()){
 	        		doesRecur.setChecked(true);
 	        	}
 	        	deleteButton.setEnabled(true);
 	        	deleteButton.setVisibility(View.VISIBLE);
 	        	registerButton.setText("Update");
 	        	
	        	deleteButton.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						try{
							thisTask.delete();
							User.getCurrentUser().refresh();
						}
						catch(Exception e){
							e.printStackTrace();
						}
		        			Intent intent = new Intent(v.getContext(), TabsActivity.class); 
			        		intent.putExtra("TAB_NUMBER", 0);
			        		startActivity(intent);
			        		finish();
					}
				});
	        }
 	        else{
 	        	editing = false;
 	        	deleteButton.setEnabled(false);
 	        	deleteButton.setVisibility(View.GONE);
 	        	
 	        	registerButton.setText("Create Task");
	        }

	        /*=============================================================================================================================
	        *get categories
	        *============================================================================================================================*/
	        ForeignCollection<Category> categoriesList = null;
	        try {
	        	categoriesList = User.getCurrentUser().getCategories();
	        } catch (Exception e) {}
	        
    		categories = new ArrayList<Category>();
    		
    		String[] categoriesAsStrings = new String[1];
    		if (categoriesList != null) {
	    		categoriesAsStrings = new String[categoriesList.size() + 1];
	    		int i = 1;
	    		for (Category c : categoriesList) {
	    			categoriesAsStrings[i] = c.toString();
	    			categories.add(c);
	    			i++;
	    		}
    		}
    		
    		categoriesAsStrings[0] = "Choose a category...";
    		ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(NewTaskActivity.this, android.R.layout.simple_spinner_item, categoriesAsStrings);
    		categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            categorySpinner.setAdapter(categoryAdapter);

            /*=============================================================================================================================
	        *get current date
	        *============================================================================================================================*/
	        final Calendar c = Calendar.getInstance();
	        year = c.get(Calendar.YEAR);
	        month = c.get(Calendar.MONTH);
	        day = c.get(Calendar.DAY_OF_MONTH);

      
	        cancelButton.setOnClickListener(new Button.OnClickListener()
	        {
	        	public void onClick(View v)
	        	{
	        		Intent intent = new Intent(v.getContext(), TabsActivity.class);
	        		intent.putExtra("TAB_NUMBER", 0);
	        		startActivity(intent);
	        		finish();
	        	}
	        });
	               
	        /*=============================================================================================================================
	        *get priorities
	        *============================================================================================================================*/
	        String[] priorities = new String[Priority.priorityStrings.length + 1];
    		int j = 1;
    		for (String p : Priority.priorityStrings) {
    			priorities[j] = p;
    			j++;
    		}
    		priorities[0] = "Choose a priority...";
    		ArrayAdapter<String> priorityAdapter = new ArrayAdapter<String>(NewTaskActivity.this, android.R.layout.simple_spinner_item, priorities);
    		priorityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            prioritySpinner.setAdapter(priorityAdapter);
	        

 	        registerButton.setOnClickListener(new Button.OnClickListener()
	        {
	        	public void onClick(View v)
	        	{   
	        		boolean validInfo = true;
	        		
	        		
	        		if(teaserField.getText().toString().length() <= 0)
	        		{
	        			validInfo = false;
	        			teaserMessage.setText("Teaser Required");
	        			teaserMessage.setTextColor(Color.RED);
	        		}
	        		
	        		else
	        		{
	        			teaserMessage.setText("Teaser");
	        			teaserMessage.setTextColor(Color.WHITE);
	        		}
	        		
	        		if(validInfo == true)
	        		{
	        			if (editing){
							try {
								thisTask.delete();
							} catch (SQLException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
	        			}
	        			if (!editing)
	        				thisTask = new Task();
	        			
	        			thisTask.setTeaser(teaserField.getText().toString());
	        			thisTask.setDescription(descriptionField.getText().toString());
	        			thisTask.setComments(commentField.getText().toString());
	        			thisTask.setCompleted(completed.isChecked());
	        			thisTask.setDoesRecur(doesRecur.isChecked());
	        			thisTask.setDueDate(taskDate);
	        			if (!editing)
	        				thisTask.setUser(User.getCurrentUser());
	        			
	        			if (locationAddress.getText().toString().length() > 0) {
	        				Location location = new Location(locationAddress.getText().toString());
	        				location.ping(getBaseContext());
	        				try {
								location.create();
								thisTask.setLocation(location);
							} catch (SQLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	        			}
	        			
	        			if (categorySpinner.getSelectedItemPosition() > 0) {
	        				thisTask.setCategory(categories.get(categorySpinner.getSelectedItemPosition() - 1));
	        			}
	        			
	        			if (prioritySpinner.getSelectedItemPosition() > 0) {
	        				thisTask.setPriority(prioritySpinner.getSelectedItemPosition());
	        				Log.d("Priority","priority" + thisTask.getPriority());
	        			}
	        			
	        			try 
	        			{
	        				thisTask.create();
	        				thisTask.getUser().refresh();	        				
						} 
	        			catch (SQLException e)
	        			{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	        			
	        			Intent intent = new Intent(v.getContext(), TabsActivity.class); 
		        		intent.putExtra("TAB_NUMBER", 0);
		        		startActivity(intent);
		        		finish();
	        		}
	        		
	        		else
	        		{
	        			teaserField.setText("");
	        		}
	        	
	           	}
	        });
	        
	        duedateButton.setOnClickListener(new View.OnClickListener()
	        {
	            public void onClick(View v) 
	            {
	                showDialog(DATE_DIALOG_ID);
	            }
	        });  
	        
	        getCurrentLocation.setOnClickListener(new Button.OnClickListener()
	        {
	        	public void onClick(View v)
	        	{
	        		String provider = LocationManager.GPS_PROVIDER;
	        		LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
	        		android.location.Location location = lm.getLastKnownLocation(provider);
	        		if (location != null) {
		        		double latitude = location.getLatitude();
		        		double longitude = location.getLongitude();
		        		List<Address> as = null;
		        		Geocoder gc = new Geocoder(getBaseContext(), Locale.getDefault());
		        		try {
		        			as = gc.getFromLocation(latitude, longitude, 1);
		        		} catch (IOException e) {}
		        		Address a = as.get(0);
		        		locationAddress.setText(""+a.getLatitude()+", "+a.getLongitude());
	        		}
	        	}
	        });
} 
}
